package com.handu.luna.boss.controller.support;

import java.util.Iterator;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import com.handu.luna.boss.controller.BossModel;
import com.handu.luna.core.domain.Page;

@Aspect
@Component
public class PageNumberUpdateAspector {
	
	@Around("execution(* com.handu.luna.boss.controller.BrandController.index(..))")
	public Object processTx(ProceedingJoinPoint joinPoint) throws java.lang.Throwable {
		
		Object result = joinPoint.proceed(joinPoint.getArgs());  
        
        if(result instanceof BossModel){
        	BossModel model = (BossModel)result;
        	Map<String, Object> results = model.getModel();
        	Iterator<String> it = results.keySet().iterator();
        	while(it.hasNext()){
        		Object attributeValue = results.get(it.next());
        		if(attributeValue.getClass().getName().equals(Page.class.getName())){
        			if(((Page<?>)attributeValue).getContent().size() == 0){
        				Object[] params = joinPoint.getArgs();
        				for (int i=0;i<params.length;i++) {
							if(params[i] instanceof Pageable){
								if(((Pageable) params[i]).hasPrevious()){
									params[i] = ((Pageable) params[i]).previousOrFirst();
									result = joinPoint.proceed(params);
									break;
								}
							}
						}
        				break;
        			}
        		}
        	}
        }

        return result;
	}
	
}
